package org.example.hotel.service;

import org.example.hotel.config.SystemStatus;
import org.example.hotel.dto.RoomStatusDTO;
import org.example.hotel.dto.TotalCostDTO;
import org.example.hotel.entity.Room;
import org.example.hotel.repository.RoomRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class AdminService {

    @Autowired
    private RoomRepository roomRepository;

    @Autowired
    private SystemStatus systemStatus;

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private RoomControlService roomControlService;


    public List<RoomStatusDTO> getAllRoomStatus() {
        List<Room> rooms = roomRepository.findAll();
        return rooms.stream().map(room -> {
            // 获取当前房间的总空调费用
            TotalCostDTO totalCostDTO = roomControlService.getCurrentTotalCost(room.getRoomId());
            double totalAcCost = totalCostDTO.getAcCost();

            return new RoomStatusDTO(
                    room.getRoomId(),
                    room.getCurrentTemp(),
                    room.getTargetTemp(),
                    room.getFanSpeed(),
                    room.isServing(),
                    room.isAcOn(),
                    room.getWorkMode(),
                    totalAcCost  // 新增的空调总费用字段
            );
        }).collect(Collectors.toList());
    }
    public void startSystem() {
        systemStatus.startSystem();
    }

    public void stopSystem() {
        systemStatus.stopSystem();

        // 关闭所有房间空调
        List<Room> allRooms = roomRepository.findAll();
        for (Room room : allRooms) {
            scheduleService.releaseRoom(room.getRoomId());
            room.setAcOn(false);
            roomRepository.save(room);
        }
    }


    public boolean getSystemStatus() {
        return systemStatus.isSystemRunning();
    }
}